package dawnland03.model.task;

import dawnland03.model.action.Action;
import dawnland03.model.action.impl.ActionFactory;
import dawnland03.model.action.parameter.ActionOutputParam;
import dawnland03.model.action.parameter.OutputParameters;
import dawnland03.model.entity.Entity;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Jan 21, 2010
 * Time: 11:10:19 PM
 */
public class BaseTask extends Task {

    private final CountDownLatch waitForActionEnd;
    private Action action; //action which will be handled by this task

    public BaseTask(String name, Entity entity, Action action) {
        super(name, entity);
        waitForActionEnd = new CountDownLatch(1);
        initBaseTask(action);
    }

    private void initBaseTask(Action action) {
        this.action = action;
        action.setParentBaseTask(this);
    }

    @Override
    protected void doNextStep() {
        if (getTaskStatus() == TaskStatus.RUNNING) {
            action.act();
            try {
                waitForActionEnd.await();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        if (getTaskStatus() == TaskStatus.FINISHED.getBeforeStatus()) {
            outputParameters.addOutputParamValues(action.getOutputParameters());
        }
        super.doNextStep();
    }

    protected final boolean isGroupTask() {
        return false;
    }

    @Override
    protected Task duplicate() {
        BaseTask duplicatedBaseTask = new BaseTask(this.name, this.entity, ActionFactory.duplicate(this.action));
        for (Map.Entry<TaskStatus, TaskCondition> statusTaskConditionEntry : afterStatusCondition.entrySet()) {
            duplicatedBaseTask.addTaskConditionAfterTaskStatus(statusTaskConditionEntry.getKey(), statusTaskConditionEntry.getValue());
        }
        return duplicatedBaseTask;
    }

    public void signalActionEnd() {
        waitForActionEnd.countDown();
    }
}
